package com.yunxin.common.utils;

import com.yunxin.common.exception.BusinessException;
import com.yunxin.common.result.PageResult;
import com.yunxin.common.result.Result;
import com.yunxin.common.result.ResultCode;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Supplier;

/**
 * @author zero°
 * @since 2023-05-29
 */
@Slf4j
public enum ResultHandleUtils {

    /**
     * 实例
     */
    X;

    /**
     * 获取结果
     * @param supplier supplier
     * @return <T> T
     */
    public <T> T getResult(Supplier<Result<T>> supplier, String errorMsg) {
        final Result<T> result = supplier.get();
        if (!ResultCode.SUCCESS.getCode().equals(result.getCode())) {
            log.warn(errorMsg, result);
            throw new BusinessException(result.getMsg());
        }
        return result.getData();
    }

    /**
     * 获取分页结果
     * @param supplier supplier
     * @return PageResult.Data<T>
     */
    public <T> PageResult.Data<T> getPageResult(Supplier<PageResult<T>> supplier, String errorMsg) {
        final PageResult<T> result = supplier.get();
        if (!ResultCode.SUCCESS.getCode().equals(result.getCode())) {
            log.warn(errorMsg, result);
            throw new BusinessException(result.getMsg());
        }
        return result.getData();
    }

}
